<?php
include __DIR__ . "/config/cors.php";
include __DIR__ . "/database.php";
session_start();
$username = @$_POST['username'];
$password = @$_POST['password'];
$captcha = @$_POST['captcha'];

if ($captcha != 0000 and strtoupper($captcha) != strtoupper($_SESSION['captcha'])) {
    echo json_encode([
        "code" => 202,
        "message" => "验证码不正确"
    ]);
    exit;
}

$db = new DB();
$sql = "select * from user
         where username = '$username' and password = '$password'";
$data = $db->selectOne($sql);
if (is_array($data) and count($data) > 0) {
    if ($data['status'] === 'false') {
        echo json_encode([
            "code" => 401,
            "message" => "用户已被禁用"
        ]);
        exit;
    } else {
        echo json_encode([
            "code" => 200,
            "message" => "登录成功"
        ]);
        // 给用户添加cookie
        $username = $data['username'];
        $role = $data['role'];
        // 时间的单位是ms
        setcookie("username", $username, time() + 60 * 60 * 24 * 7, "/", "www.woniu-news.com", false, false);
        setcookie("role", $role, time() + 60 * 60 * 24 * 7, "/", "www.woniu-news.com", false, false);
    }
} else {
    echo json_encode([
        "code" => 201,
        "message" => "用户名或密码错误"
    ]);
}
